// 全局变量
let currentUser = null;
let currentStudent = null;

// API基础URL
const API_BASE = window.location.origin;

// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

function initializeApp() {
    // 绑定事件监听器
    bindEvents();

    // 检查是否已登录（简化版，实际应该检查session/token）
    const savedUser = localStorage.getItem('currentUser');
    if (savedUser) {
        currentUser = JSON.parse(savedUser);
        showMainSection();
        loadStudentInfo();
        loadCourses();
    }
}

function bindEvents() {
    // 登录表单
    const loginForm = document.getElementById('login-form');
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
    }

    // 导航按钮
    document.getElementById('courses-btn').addEventListener('click', () => {
        showSection('courses-section');
        loadCourses();
    });

    document.getElementById('my-courses-btn').addEventListener('click', () => {
        showSection('my-courses-section');
        loadMyCourses();
    });

    document.getElementById('profile-btn').addEventListener('click', () => {
        showSection('profile-section');
        loadProfile();
    });

    document.getElementById('logout-btn').addEventListener('click', handleLogout);

    // 搜索功能
    document.getElementById('search-btn').addEventListener('click', handleSearch);
    document.getElementById('search-input').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            handleSearch();
        }
    });

    // 模态框
    const modal = document.getElementById('course-modal');
    const closeBtn = modal.querySelector('.close');
    closeBtn.addEventListener('click', () => {
        modal.style.display = 'none';
    });

    document.getElementById('cancel-select').addEventListener('click', () => {
        modal.style.display = 'none';
    });

    document.getElementById('confirm-select').addEventListener('click', handleConfirmSelect);

    // 点击模态框外部关闭
    window.addEventListener('click', function(e) {
        if (e.target === modal) {
            modal.style.display = 'none';
        }
    });
}

// 登录处理
async function handleLogin(e) {
    e.preventDefault();

    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    if (!username || !password) {
        showMessage('login-message', '请输入用户名和密码', 'error');
        return;
    }

    try {
        const response = await fetch(`${API_BASE}/api/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`
        });

        const result = await response.json();

        if (result.success) {
            currentUser = result.user;
            localStorage.setItem('currentUser', JSON.stringify(currentUser));
            showMainSection();
            loadStudentInfo();
            loadCourses();
        } else {
            showMessage('login-message', result.message || '登录失败', 'error');
        }
    } catch (error) {
        console.error('Login error:', error);
        showMessage('login-message', '网络错误，请重试', 'error');
    }
}

// 退出登录
function handleLogout() {
    currentUser = null;
    currentStudent = null;
    localStorage.removeItem('currentUser');
    document.getElementById('login-section').style.display = 'block';
    document.getElementById('main-section').style.display = 'none';
    document.getElementById('login-form').reset();
}

// 显示主界面
function showMainSection() {
    document.getElementById('login-section').style.display = 'none';
    document.getElementById('main-section').style.display = 'block';
}

// 显示指定section
function showSection(sectionId) {
    // 隐藏所有content sections
    const sections = document.querySelectorAll('.content-section');
    sections.forEach(section => {
        section.style.display = 'none';
    });

    // 移除所有nav按钮的active类
    const navBtns = document.querySelectorAll('.nav-btn');
    navBtns.forEach(btn => {
        btn.classList.remove('active');
    });

    // 显示指定section
    document.getElementById(sectionId).style.display = 'block';

    // 添加对应的nav按钮active类
    const navBtnId = sectionId.replace('-section', '-btn');
    document.getElementById(navBtnId).classList.add('active');
}

// 加载学生信息
async function loadStudentInfo() {
    if (!currentUser) return;

    try {
        const response = await fetch(`${API_BASE}/api/student/info?user_id=${currentUser.id}`);
        const result = await response.json();

        if (result.success) {
            currentStudent = result.data;
        }
    } catch (error) {
        console.error('Load student info error:', error);
    }
}

// 加载课程列表
async function loadCourses(searchKeyword = '') {
    const coursesList = document.getElementById('courses-list');
    coursesList.innerHTML = '<div class="loading"></div>';

    try {
        let url = `${API_BASE}/api/courses`;
        if (searchKeyword) {
            url += `?search=${encodeURIComponent(searchKeyword)}`;
        }

        const response = await fetch(url);
        const result = await response.json();

        if (result.success) {
            displayCourses(result.data, coursesList);
        } else {
            coursesList.innerHTML = '<div class="empty-state"><h3>加载失败</h3><p>无法加载课程列表</p></div>';
        }
    } catch (error) {
        console.error('Load courses error:', error);
        coursesList.innerHTML = '<div class="empty-state"><h3>网络错误</h3><p>请检查网络连接后重试</p></div>';
    }
}

// 显示课程列表
function displayCourses(courses, container) {
    if (courses.length === 0) {
        container.innerHTML = '<div class="empty-state"><h3>暂无课程</h3><p>当前没有可选课程</p></div>';
        return;
    }

    container.innerHTML = '';

    courses.forEach(course => {
        const courseCard = createCourseCard(course, false);
        container.appendChild(courseCard);
    });
}

// 创建课程卡片
function createCourseCard(course, isMyCourse = false) {
    const courseCard = document.createElement('div');
    courseCard.className = 'course-card';

    const statusClass = course.status === '可选' ? 'status-available' :
                       course.status === '已满' ? 'status-full' : 'status-cancelled';

    let actionButtons = '';
    if (!isMyCourse && currentUser && currentUser.role === 'student' && course.status === '可选') {
        actionButtons = `<button class="btn btn-success" onclick="showSelectModal(${course.id}, '${course.course_name}', '${course.description || ''}')">选课</button>`;
    } else if (isMyCourse) {
        actionButtons = `<button class="btn btn-danger" onclick="dropCourse(${course.id})">退选</button>`;
    }

    courseCard.innerHTML = `
        <div class="course-header">
            <div class="course-title">${course.course_name}</div>
            <div class="course-code">${course.course_code}</div>
        </div>
        <div class="course-info">
            <p><strong>教师：</strong>${course.teacher_name || '暂无'}</p>
            <p><strong>学分：</strong>${course.credits}</p>
            <p><strong>学期：</strong>${course.semester}</p>
            <p><strong>教室：</strong>${course.classroom}</p>
            <p><strong>时间：</strong>${course.schedule}</p>
            <p><strong>已选/容量：</strong>${course.current_students}/${course.max_students}</p>
        </div>
        <div class="course-status ${statusClass}">${course.status}</div>
        <div class="course-actions">
            ${actionButtons}
        </div>
    `;

    return courseCard;
}

// 搜索课程
function handleSearch() {
    const searchInput = document.getElementById('search-input');
    const keyword = searchInput.value.trim();
    loadCourses(keyword);
}

// 显示选课模态框
function showSelectModal(courseId, courseName, description) {
    const modal = document.getElementById('course-modal');
    document.getElementById('modal-course-name').textContent = courseName;
    document.getElementById('modal-course-details').innerHTML = description || '暂无详细描述';

    // 存储当前课程ID
    modal.dataset.courseId = courseId;

    modal.style.display = 'block';
}

// 确认选课
async function handleConfirmSelect() {
    const modal = document.getElementById('course-modal');
    const courseId = parseInt(modal.dataset.courseId);

    if (!currentStudent) {
        alert('学生信息加载失败，请重新登录');
        return;
    }

    try {
        const response = await fetch(`${API_BASE}/api/select-course`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `student_id=${currentStudent.id}&course_id=${courseId}`
        });

        const result = await response.json();

        if (result.success) {
            alert('选课成功！');
            modal.style.display = 'none';
            loadCourses(); // 重新加载课程列表
        } else {
            alert('选课失败：' + (result.message || '未知错误'));
        }
    } catch (error) {
        console.error('Select course error:', error);
        alert('网络错误，请重试');
    }
}

// 退选课程
async function dropCourse(courseId) {
    if (!currentStudent) {
        alert('学生信息加载失败，请重新登录');
        return;
    }

    if (!confirm('确定要退选这门课程吗？')) {
        return;
    }

    try {
        const response = await fetch(`${API_BASE}/api/drop-course`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `student_id=${currentStudent.id}&course_id=${courseId}`
        });

        const result = await response.json();

        if (result.success) {
            alert('退选成功！');
            loadMyCourses(); // 重新加载我的课程
        } else {
            alert('退选失败：' + (result.message || '未知错误'));
        }
    } catch (error) {
        console.error('Drop course error:', error);
        alert('网络错误，请重试');
    }
}

// 加载我的课程
async function loadMyCourses() {
    if (!currentUser) return;

    const myCoursesList = document.getElementById('my-courses-list');
    myCoursesList.innerHTML = '<div class="loading"></div>';

    try {
        const response = await fetch(`${API_BASE}/api/student/courses?user_id=${currentUser.id}`);
        const result = await response.json();

        if (result.success) {
            displayMyCourses(result.data, myCoursesList);
        } else {
            myCoursesList.innerHTML = '<div class="empty-state"><h3>加载失败</h3><p>无法加载已选课程</p></div>';
        }
    } catch (error) {
        console.error('Load my courses error:', error);
        myCoursesList.innerHTML = '<div class="empty-state"><h3>网络错误</h3><p>请检查网络连接后重试</p></div>';
    }
}

// 显示我的课程
function displayMyCourses(courses, container) {
    if (courses.length === 0) {
        container.innerHTML = '<div class="empty-state"><h3>暂无选课</h3><p>您还没有选择任何课程</p></div>';
        return;
    }

    container.innerHTML = '';

    courses.forEach(course => {
        const courseCard = createCourseCard(course, true);
        container.appendChild(courseCard);
    });
}

// 加载个人信息
async function loadProfile() {
    if (!currentUser || !currentStudent) {
        document.getElementById('profile-info').innerHTML = '<p>信息加载失败，请重新登录</p>';
        return;
    }

    const profileInfo = document.getElementById('profile-info');
    profileInfo.innerHTML = `
        <div class="profile-field">
            <span class="profile-label">学号：</span>
            <span class="profile-value">${currentStudent.student_id}</span>
        </div>
        <div class="profile-field">
            <span class="profile-label">姓名：</span>
            <span class="profile-value">${currentStudent.name}</span>
        </div>
        <div class="profile-field">
            <span class="profile-label">性别：</span>
            <span class="profile-value">${currentStudent.gender}</span>
        </div>
        <div class="profile-field">
            <span class="profile-label">班级：</span>
            <span class="profile-value">${currentStudent.class_name || '未设置'}</span>
        </div>
        <div class="profile-field">
            <span class="profile-label">邮箱：</span>
            <span class="profile-value">${currentStudent.email || '未设置'}</span>
        </div>
        <div class="profile-field">
            <span class="profile-label">电话：</span>
            <span class="profile-value">${currentStudent.phone || '未设置'}</span>
        </div>
        <div class="profile-field">
            <span class="profile-label">用户角色：</span>
            <span class="profile-value">${getRoleDisplayName(currentUser.role)}</span>
        </div>
    `;
}

// 获取角色显示名称
function getRoleDisplayName(role) {
    const roleMap = {
        'student': '学生',
        'teacher': '教师',
        'admin': '管理员'
    };
    return roleMap[role] || role;
}

// 显示消息
function showMessage(elementId, message, type = 'info') {
    const element = document.getElementById(elementId);
    element.textContent = message;
    element.className = `message ${type}`;

    // 3秒后自动隐藏
    setTimeout(() => {
        element.textContent = '';
        element.className = 'message';
    }, 3000);
}
